package hcd.mynote;


import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.*;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import org.json.JSONObject;


/**
 * A simple {@link Fragment} subclass.
 */
public class UserFragment extends Fragment {

//    LinearLayout userLayout;
//    LinearLayout loginLayout;
    private OnUserChangeListener userChangeListener;
    private boolean toggleReg = false;

    private EditText usernameInput;
    private EditText passwordInput;
    private EditText passwordAgainInput;
    private Button actionBtn;
    private Button toggleBtn;

    private boolean isUsernameOK = false;

    public UserFragment() {
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        getActivity().setTitle("用户");
        setHasOptionsMenu(true);
        ((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        // Inflate the layout for this fragment
        final View view = inflater.inflate(R.layout.fragment_user, container, false);
        SharedPreferences sp = getActivity().getSharedPreferences("user", Context.MODE_PRIVATE);
        final String username = sp.getString("username", null);
        if (username == null){
            view.findViewById(R.id.login_panel).setVisibility(View.VISIBLE);
        }else {
            view.findViewById(R.id.user_panel).setVisibility(View.VISIBLE);

        }

        usernameInput = (EditText) view.findViewById(R.id.username_input);
        passwordInput = (EditText) view.findViewById(R.id.password_input);
        passwordAgainInput = (EditText) view.findViewById(R.id.password_again_input);
        actionBtn = (Button) view.findViewById(R.id.login_reg_action_btn);
        toggleBtn = (Button) view.findViewById(R.id.toggle_login_reg_btn);
        toggleBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                ((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(usernameInput.getWindowToken(), 0);
                ((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(passwordInput.getWindowToken(), 0);
                ((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(passwordAgainInput.getWindowToken(), 0);


                toggleReg = !toggleReg;
                if (toggleReg){
                    passwordAgainInput.setVisibility(View.VISIBLE);
                    actionBtn.setText(R.string.action_btn_reg);
                    toggleBtn.setText(R.string.toggle_btn_login);
                }else {
                    passwordAgainInput.setText("");
                    passwordAgainInput.setVisibility(View.GONE);
                    actionBtn.setText(R.string.action_btn_login);
                    toggleBtn.setText(R.string.toggle_btn_reg);
                }
            }
        });

        usernameInput.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus){
                    checkUsername();
                }else {
                    isUsernameOK = false;
                    usernameInput.setError(null, null);
                }
            }
        });
        passwordInput.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) passwordInput.setError(null, null);
            }
        });
        passwordAgainInput.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) passwordAgainInput.setError(null, null);
            }
        });

        actionBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(usernameInput.getWindowToken(), 0);
                ((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(passwordInput.getWindowToken(), 0);
                ((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(passwordAgainInput.getWindowToken(), 0);

                doAction();
            }
        });

        TextView userLabel = (TextView) view.findViewById(R.id.username_label);
        userLabel.setText("用户: " + username);
        view.findViewById(R.id.quit_login_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences.Editor editor = getActivity().getSharedPreferences("user", Context.MODE_PRIVATE).edit();
                editor.remove("username");
                editor.apply();

                userChangeListener.change();

                view.findViewById(R.id.login_panel).setVisibility(View.VISIBLE);
                view.findViewById(R.id.user_panel).setVisibility(View.GONE);

            }
        });

        return view;
    }

    private boolean checkInput(){
        if(!checkUsername()) return false;
        if (toggleReg) if (!isUsernameOK) return false;

        String inputPassword = passwordInput.getText().toString();
        if (inputPassword.isEmpty()) {
            passwordInput.setError("请输入密码");
            return false;
        }
        if (toggleReg){
            String inputPasswordAgain = passwordAgainInput.getText().toString();
            if (!inputPasswordAgain.equals(inputPassword)){
                passwordAgainInput.setError("密码不一致");
                return false;
            }
        }
        return true;
    }

    private boolean checkUsername(){
        String inputUsername = usernameInput.getText().toString();
        if (!inputUsername.isEmpty()){
            usernameInput.setError(null, null);

            if (toggleReg){
                new Thread(){
                    @Override
                    public void run() {
                        super.run();
                        String inputUsername = usernameInput.getText().toString();
                        try {
                            JSONObject user = Bmob.userQuery(inputUsername);
                            if (user != null) {
//                        usernameInput.setError("该用户已存在");
                                isUsernameOK = false;
                                checkUsernameHandler.obtainMessage(1).sendToTarget();
                            } else {
//                        usernameInput.setError(null);
                                isUsernameOK = true;
                                checkUsernameHandler.obtainMessage(0).sendToTarget();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
//                    usernameInput.setError(null);
                            isUsernameOK = true;
                            checkUsernameHandler.obtainMessage(0).sendToTarget();
                        }
                    }
                }.start();
            }
            return true;
        }else {
            usernameInput.setError("请输入用户名");
            return false;
        }

    }

    private Handler checkUsernameHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0){
                usernameInput.setError(null, null);
            }else {
                usernameInput.setError("该用户已存在");
            }
        }
    };

    private void doAction(){
        if (!checkInput()) return;
        actionBtn.setEnabled(false);
        toggleBtn.setEnabled(false);
        new Thread(){
            @Override
            public void run() {
                super.run();
                String inputUsername = usernameInput.getText().toString();
                String inputPassword = passwordInput.getText().toString();
                if (!toggleReg){
                    try {
                        int result = Bmob.login(inputUsername, inputPassword);
                        actionHandler.obtainMessage(result).sendToTarget();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }else {
                    actionHandler.obtainMessage(Bmob.register(inputUsername, inputPassword) ? 0:1).sendToTarget();
                }

            }
        }.start();


    }

    private Handler actionHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            actionBtn.setEnabled(true);
            toggleBtn.setEnabled(true);
            if (!toggleReg){
                if (msg.what == 0){
                    Toast.makeText(getContext(), "登陆成功", Toast.LENGTH_SHORT).show();
                    finishAction();
                }else if (msg.what == 1){
                    usernameInput.setError("用户名不存在");
                }else if (msg.what == 2){
                    passwordInput.setError("密码不正确");
                }
            }else {
                if (msg.what == 0){
                    Toast.makeText(getContext(), "注册成功", Toast.LENGTH_SHORT).show();
                    finishAction();
                }else {
                    usernameInput.setError("出错了");
                }
            }
        }
    };

    private void finishAction(){

        SharedPreferences.Editor editor = getActivity().getSharedPreferences("user", Context.MODE_PRIVATE).edit();
        editor.putString("username", usernameInput.getText().toString());
        editor.apply();

        userChangeListener.change();

        getActivity().getSupportFragmentManager().popBackStack();
    }

    public OnUserChangeListener getUserChangeListener() {
        return userChangeListener;
    }

    public void setUserChangeListener(OnUserChangeListener userChangeListener) {
        this.userChangeListener = userChangeListener;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                getActivity().getSupportFragmentManager().popBackStack();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
//        usernameInput.clearFocus();
//        passwordInput.clearFocus();
//        passwordAgainInput.clearFocus();
        ((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(usernameInput.getWindowToken(), 0);
        ((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(passwordInput.getWindowToken(), 0);
        ((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(passwordAgainInput.getWindowToken(), 0);

        try{
            userChangeListener.back();
            // 显示主页的导航栏的内容
            getActivity().setTitle("我的笔记");
            ((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(false);

            // 更改当前为主页
            ((HomeActivity) getActivity()).setCurrentFragment(HomeActivity.HOME_FRAGMENT);

            // 更新导航栏
            getActivity().getWindow().invalidatePanelMenu(Window.FEATURE_OPTIONS_PANEL);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
